package main

import (
	"fmt"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/constants"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/message"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/netWork"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/server/processes"
	"io"
)

type Processor struct {
	Conn netWork.Conn
}

func (p *Processor) Process() error {
	for {
		// 读取数据包，直接封装成一个函数，返回message和error
		req, err := p.Conn.Get()
		if err != nil {
			if err == io.EOF {
				return err
			}
		} else {
			err = p.ServerProcessMsg(req)
			if err != nil {
				return err
			}
		}
	}
}

func (p *Processor) ServerProcessMsg(req message.Message) (err error) {
	switch req.Type {
	case constants.MSG_TYPE_LOGIN_REQ:
		// 登陆
		userProcess := processes.UserProcess{Conn: p.Conn}
		err = userProcess.ServerLoginProcess(req.Data)
	case constants.MSG_TYPE_REGISTER_REQ:
		userProcess := processes.UserProcess{Conn: p.Conn}
		userProcess.ServerRegisterProcess(req.Data)
	case constants.MSG_TYPE_SMS_MSG:
		fmt.Println("MSG_TYPE_SMS_MSG:", req.Data)
		smsProcess := processes.SmsProcess{}
		smsProcess.ForwardGroupMsg(req.Data)
	default:
		errProcess := processes.ErrorProcess{Conn: p.Conn}
		err = errProcess.ServerErrorProcess()
	}
	return
}
